package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"home-mgr-sys/homerpc/homerpc"
	"home-mgr-sys/homerpc/internal/svc"
	"home-mgr-sys/models/cache"
	"home-mgr-sys/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type HomeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHomeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HomeListLogic {
	return &HomeListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HomeListLogic) HomeList(in *homerpc.HomeListRequest) (*homerpc.HomeListResponse, error) {
	// todo: add your logic here and delete this line
	var home mysql.Home
	var list []*homerpc.HomeList
	sprintf := fmt.Sprintf("home%s", in)
	result, _ := cache.Rdb.Get(cache.Ctx, sprintf).Result()
	if result == "" {
		var err error
		list, err = home.HomeList(mysql.DB, in, list)
		if err != nil {
			return nil, err
		}
		marshal, err := json.Marshal(&list)
		if err != nil {
			return nil, err
		}
		cache.Rdb.Set(cache.Ctx, sprintf, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}
	return &homerpc.HomeListResponse{
		List: list,
	}, nil
}
